<?php
/**
 * 自动扣款
 * @author GRAY
 */

namespace Console\Controller;

use Common\Library\Constant;
use Think\Log;
use Common\Library\SendSMS;

class AutoPayController extends CronController
{

    private $_repaymentDate = '';
    private $_repaymentTime = '';

    public function __construct()
    {
        parent::__construct();
        //固定还款日
        $this->_repaymentDate = date('Y-m-' . Constant::BILL_LAST_DAY);

        $this->_repaymentTime = strtotime($this->_repaymentDate);
    }

// cd /home/wwwroot/default/apitest/ && /usr/local/php/bin/php -f /home/wwwroot/default/apitest/console.php /AutoPay/exepay1
    function exepay() {
        $today = date('Ymd');
        $this->execute($today);
    
    }
    function exepay2() {
        $yesterday = date("Ymd",strtotime("-1 day"));
        $this->execute($yesterday);
    }
    function execute($today) {      
        $sql = "SELECT a.parent_id,b.type,b.customer_id,a.id,a.amount,a.repayment_time FROM `consume_installment_history` a 
                left join consume_history b on (b.id = a.parent_id)
                WHERE FROM_UNIXTIME( b.repayment_time,  '%Y%m%d' ) =  '$today' and a.status =0
                and b.type in(2,5) and b.status in(1,4)
                and b.customer_id in (SELECT c.`customer_id` FROM `customer_bank_info` c left join `customer` d on (d.id = .c.`customer_id`) WHERE  d.`id`>0 and d.`type`=1) order by b.customer_id";
        $result = M()->query($sql);

        $customer_arr= array();
        foreach($result as $v) {
            if(!in_array($v['customer_id'],$customer_arr)) {
                $xml_data[$v['customer_id']] = array(
                    "customer_id"=>$v['customer_id'], //955
                    "pay_pass"=>"",
                    "paytype"=>"1",
                    "type"=>"1",
                    "check_pass"=>"no",
                    "pay_action"=>"2",
                    "consume_data"=>array(
                            array(
                                "consume_id"=>$v['parent_id'],
                                "type"=>$v['type'],//1消费次月还款 2消费分期还款 5现金贷分期还款
                                "repay_date"=>"",
                                "amount"=>"",
                                "overdue_amount"=>"",
                                "installment_history"=>array(
                                        array("id"=>$v['id'],"repay_date"=>date("Y-m-d",$v['repayment_time']),"amount"=>$v['amount'],"overdue_amount"=>"0"),
                            )
                        )
                    )
                );
                $customer_arr[] = $v['customer_id'];
            } else {
                $xml_data[$v['customer_id']]['consume_data'][]=array(
                        "consume_id"=>$v['parent_id'],
                        "type"=>$v['type'],//1消费次月还款 2消费分期还款 5现金贷分期还款
                        "repay_date"=>"",
                        "amount"=>"",
                        "overdue_amount"=>"",
                        "installment_history"=>array(
                                array("id"=>$v['id'],"repay_date"=>date("Y-m-d",$v['repayment_time']),"amount"=>$v['amount'],"overdue_amount"=>"0"),
                        )
                    );
            }
        }

        //echo "<pre>";
        //print_r($xml_data);
        //exit;

        foreach($xml_data as $v) {

            $sign = $this->genSign($v);
            $url = "http://api.huoyanzichan.com/Home/Pay/payConfirm";
            $v['sign'] = $sign;
            $pay_result = $this->curlPost($url,$v);
            $ret = json_decode(trim($pay_result,chr(239).chr(187).chr(191)),true);
            if($ret) {
                if($ret['code']==0) {
                    //发短信
                    $order_id = $ret['data']['order_id'];
                    $sql = "SELECT a.`amount`,b.mobile FROM `customer_bill_pay_log` a left join customer b on(b.id =a.`customer_id`) where `order_id`='$order_id' and `ret_msg`='success' and `pay_time`>0 and `pay_action`=2 limit 1";
                    $result_sql = M()->query($sql);
                    if($result_sql) {
                        $amount = floor($result_sql[0]['amount']/100);
                        $mobile = $result_sql[0]['mobile'];
                        $payday = date('Y年n月j日');
                        if($mobile<>'') {
                            SendSMS::smsReminder($mobile,'', $amount, $payday, '','','','100');
                        }
                    }
                } else {
                    $customerId = $ret['data']['customerId'];
                    $amount = $amount = floor($ret['data']['amount']/100);
                    $sql = "SELECT a.`gate_id`,b.`mobile` FROM `customer_bank_info` a left join customer b on(b.id =a.`customer_id`)  WHERE a.`customer_id`='$customerId' limit 1";
                    $result_sql = M()->query($sql);
                    $gate_id = $result_sql[0]['gate_id'];
                    $mobile = $result_sql[0]['mobile'];
                    $bank_arr =array(
                            'CCB'=>'建设银行',
                            'ABC'=>'农业银行',
                            'BOC'=>'中国银行',
                            'ICBC'=>'工商银行',
                            'CMB'=>'招商银行',
                            'CMBC'=>'民生银行',
                            'CEB'=>'光大银行',
                            'CIB'=>'兴业银行',
                            'GDB'=>'广发银行',
                            'SPAB'=>'平安银行',
                            'COMM'=>'交通银行',
                            'CITIC'=>'中信银行',
                            'SPDB'=>'浦发银行',
                    );
                    $bank = $bank_arr[$gate_id];
                    if($mobile<>'') {
                        SendSMS::smsReminder($mobile,'', $amount, $bank, '','','','200');
                    }
                }
            }
        }
    }
    function genSign(array $param) {
        //0. 删除原数据中自带的sign值,防止干扰计算结果
        unset($param['sign']);
        //1. 按key由a到z排序
        ksort($param);
        foreach ($param as $key => $value) {
            if (is_array($value)) {
                $param[$key] = $this->genSign($value);
            }
        }
        //2. 生成以&符链接的key=value形式的字符串
        $paramString = urldecode(http_build_query($param));

        //3. 拼接我们的服务秘钥，并md5加密
        $sign = md5($paramString . 'secret@huoyan.com');
        return $sign;
    }

    function curlPost($url,$xml_data) {
        $ch=curl_init($url); 
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        //curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        //curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);


        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($xml_data));
        $response = curl_exec($ch);
        if(curl_errno($ch))
        {
            print curl_error($ch);
        }
        curl_close($ch);
        return $response;
        print_r($response);
    }
}
